package com.ssi.mrms.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.InputStream;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;

public class CaptchaUtils {
	private static final Logger logger = Logger.getLogger(CaptchaUtils.class);
	private static final String FONT_PATH = "font/PlAGuEdEaTH.ttf";
	private static final String RANDOM_KEY = "abcdefghijklmnopqrstuvwxyz0123456789";
	private static final int MAX_CAPTCHA = 4;

	private CaptchaUtils() {
	}

	public static String getKey() {
		return RandomStringUtils.random(MAX_CAPTCHA, RANDOM_KEY);
	}

	public static BufferedImage createImage() {
		String key = RandomStringUtils.random(MAX_CAPTCHA, RANDOM_KEY);
		return createImage(key);
	}

	public static BufferedImage createImage(final String key) {
		logger.info("createImage with key " + key);
		BufferedImage bufferedImage = null;
		try (InputStream in = CaptchaUtils.class.getClassLoader().getResourceAsStream(FONT_PATH)) {
			bufferedImage = new BufferedImage(130, 30, BufferedImage.TYPE_INT_RGB);
			Graphics graphics = bufferedImage.getGraphics();
			graphics.setColor(Color.WHITE);
			graphics.fillRect(0, 0, 200, 50);
			graphics.setColor(Color.BLUE);
			Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, in);
			Font dynamicFont32Pt = dynamicFont.deriveFont(32f);
			graphics.setFont(dynamicFont32Pt);
			graphics.drawString(key, 10, 25);
			// ImageIO.write(bufferedImage, "jpg", new File("D:/image.jpg"));
			logger.info("Image Created..");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return bufferedImage;
	}

	public static void main(String[] args) {
		createImage();
	}

}
